package com.lb.service;

import com.lb.comment.Result;
import com.lb.mapper.OrderMapper;
import com.lb.mapper.StockMapper;
import com.lb.util.RedissonDistributedLockUtil;
import com.mysql.cj.x.protobuf.MysqlxCrud;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Map;
@Service
public class StockService {

    @Autowired
    private StockMapper stockMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Transactional(rollbackFor = Exception.class)
    public Result checkStock(String product_code) {
        RLock lock = null;
        try {
            lock = RedissonDistributedLockUtil.lock("order:product_code:" + product_code, 10, 3, 200);

            Map<String, Object> stockInfo = stockMapper.getStockInfo(product_code);
            int quantity = (int) stockInfo.get("stock_quantity");

            if (quantity <= 0) {
                return Result.failure("库存不足");
            }

            String orderId = RedissonDistributedLockUtil.generateId("useri", "henan");
            orderMapper.InsertOrder(orderId, product_code);
            //int i = 1 / 0; // 模拟异常
            stockMapper.updateStock(product_code);

            return Result.success("下单成功", orderId);
        } finally {
            RedissonDistributedLockUtil.unlock(lock);
        }
    }
}


